package com.ruoyi.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.injector.DefaultSqlInjector;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * @Author: seeTools
 * @Date: 2024/1/9  11:44
 * @Version 1.0
 */
@Configuration
public class MybatisConfig implements MetaObjectHandler {


    /**
     * 乐观锁配置
     *
     * @return 插件
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        //1 创建MybatisPlusInterceptor拦截器对象
        MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor();
        //2 添加乐观锁拦截器
        mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mpInterceptor;
    }


    /**
     * 分页插件。如果你不配置，分页插件将不生效
     */
    @Bean
    public MybatisPlusInterceptor paginationInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 指定数据库方言为 MYSQL
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }


    /**
     * 逻辑删除
     *
     * @return
     */
    @Bean
    public ISqlInjector sqlInjector() {
        return new DefaultSqlInjector();
    }


    /**
     * 自动填充
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        this.setFieldValByName("modifiedDate", new Date(), metaObject);
        this.setFieldValByName("createDate", new Date(), metaObject);
        this.setFieldValByName("modifierName", loginUser.getUser().getUserName(), metaObject);
        this.setFieldValByName("modifierId", loginUser.getUserId(), metaObject);
        this.setFieldValByName("creatorName", loginUser.getUser().getUserName(), metaObject);
        this.setFieldValByName("creatorId", loginUser.getUserId(), metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 获取当前登入人员
        LoginUser loginUser = SecurityUtils.getLoginUser();
        this.setFieldValByName("modifiedDate", new Date(), metaObject);
        this.setFieldValByName("modifierName", loginUser.getUser().getUserName(), metaObject);
        this.setFieldValByName("modifierId", loginUser.getUserId(), metaObject);
    }

}
